package com.example.administrator.x3picturetransliteration.Home.Activity;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.widget.TextView;

import com.example.administrator.x3picturetransliteration.Base.BaseActivity;
import com.example.administrator.x3picturetransliteration.Base.BasePresenter;
import com.example.administrator.x3picturetransliteration.Constants;
import com.example.administrator.x3picturetransliteration.Dao.Rx.GuidePageRx;
import com.example.administrator.x3picturetransliteration.Dao.Table.GuidePage;
import com.example.administrator.x3picturetransliteration.Home.Presenter.Activity.AdvertisementPresenter;
import com.example.administrator.x3picturetransliteration.Home.Presenter.Activity.MainActivityPresenter;
import com.example.administrator.x3picturetransliteration.R;

import java.util.List;

import butterknife.BindView;
import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.RuntimePermissions;
import rx.Observer;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

@RuntimePermissions
public class MainActivity extends BaseActivity {

    @BindView(R.id.gsText)TextView gsText;

    private MainActivityPresenter mMainActivityPresenter;

    private AdvertisementPresenter mAdvertisementPresenter;

     Thread go = new Thread(new Runnable() {
        @Override
        public void run() {

            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            MainActivity.this.runOnUiThread(new Runnable() {
                @Override
                public void run() {

                    MainActivityPermissionsDispatcher.BootPageDaoWithCheck(MainActivity.this);
                }
            });

        }
    });

    @Override
    public int intiLayout() {
        return R.layout.home_activity_main;
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Constants.getConstants().setChannelCode(getChannelName(this));
    }

    @Override
    protected void onStart() {
        super.onStart();

        mMainActivityPresenter = new MainActivityPresenter(this,mCompositeSubscriptions);

        mAdvertisementPresenter = new AdvertisementPresenter(this,mCompositeSubscriptions);

        mMainActivityPresenter.getAppData(new BasePresenter.Callback() {
            @Override
            public void getData(Object data) {

                String gsName = Constants.getConstants().getmAppDataBean().getCompanyName();

                if (gsName!=null)gsText.setText(gsName);
                go.start();
            }
        });
    }


    @NeedsPermission({Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE})
    public void BootPageDao(){

        mCompositeSubscriptions.add(
                new GuidePageRx().queryAll()
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new Observer<List<GuidePage>>() {
                            @Override
                            public void onCompleted() {

                            }

                            @Override
                            public void onError(Throwable e) {

                            }

                            @Override
                            public void onNext(List<GuidePage> mGuidePage) {
                                if(mGuidePage.size()!=0){

                                    mAdvertisementPresenter.ad(new BasePresenter.Callback() {
                                        @Override
                                        public void getData(Object data) {

                                            if (data==null){

                                                startActivity(new Intent(MainActivity.this,SignInActivity.class));

                                            }else {

                                                AdvertisementActivity.StartAdvertisementActivity(MainActivity.this);
                                            }

                                            MainActivity.this.finish();

                                        }
                                    });

                                } else {

                                    updateBootPageDao();
                                }
                            }
                        })
        );

    }

    private void updateBootPageDao(){

        GuidePage mGuidePage = new GuidePage();
        mGuidePage.setData("ok");

        new GuidePageRx().saveData(mGuidePage, new GuidePageRx.CallbackGuidePageRx() {
            @Override
            public void Method() {

                MainActivity.this.startActivity(new Intent(MainActivity.this,GuideActivity.class));
                MainActivity.this.finish();
            }
        });
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        // NOTE: delegate the permission handling to generated method
        MainActivityPermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
    }

    //获取渠道名称
    public static String getChannelName(Activity ctx) {
        if (ctx == null) {
            return null;
        }
        String channelName = "";
        try {
            PackageManager packageManager = ctx.getPackageManager();
            if (packageManager != null) {
                //注意此处为ApplicationInfo 而不是 ActivityInfo,因为友盟设置的meta-data是在application标签中，而不是某activity标签中，所以用ApplicationInfo
                ApplicationInfo applicationInfo = packageManager.getApplicationInfo(ctx.getPackageName(), PackageManager.GET_META_DATA);
                if (applicationInfo != null) {
                    if (applicationInfo.metaData != null) {
                        channelName = applicationInfo.metaData.getString("UMENG_CHANNEL");
                    }
                }

            }
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return channelName;
    }
}
